package com.dubbo.gmail.provider.serviceImp;

import com.dubbo.gmail.api.service.AsyncHelloService;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.rpc.AsyncContext;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.stereotype.Component;

import java.util.concurrent.CompletableFuture;

@DubboService(timeout = 10000, async = true)
@Component
public class AsyncHelloServiceImpl implements AsyncHelloService {
    @Override
    public CompletableFuture<String> sayHelloAsync(String word) {
        RpcContext savedContext = RpcContext.getContext();
        // 建议为supplyAsync提供自定义线程池，避免使用JDK公用线程池
        return CompletableFuture.supplyAsync(() -> {
            System.out.println(savedContext.getAttachment("consumer-key1"));
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "async response from provider." + word;
        });
    }

    @Override
    public CompletableFuture<String> sayHelloContextAsync(String word) {
        final AsyncContext asyncContext = RpcContext.startAsync();
        new Thread(() -> {
            // 如果要使用上下文，则必须要放在第一句执行
            asyncContext.signalContextSwitch();
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 写回响应
            asyncContext.write("Hello " + word + ", response from provider.");
        }).start();
        return null;
    }

    @Override
    public CompletableFuture<String> sayHelloWhenComplete(String word) {
        // 建议为supplyAsync提供自定义线程池，避免使用JDK公用线程池
        return CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "async response complete from provider." + word;
        });
    }


}
